package com.meixiang.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.activity.WebviewActivity;
import com.meixiang.activity.account.login.LoginActivity;
import com.meixiang.activity.account.manager.VerifyRealNameActivity;
import com.meixiang.activity.account.myfund.FundListMainActivity;
import com.meixiang.activity.homes.cosmeticTraining.CosmeticTrainingActivity;
import com.meixiang.activity.homes.service.ServiceActivity;
import com.meixiang.activity.homes.shopping.ShoppingHomeActivity;
import com.meixiang.adapter.home.IndexAdapter;
import com.meixiang.entity.HomeData;
import com.meixiang.global.Config;
import com.meixiang.global.ContentHint;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseFragment;
import com.meixiang.main.MXApplication;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AbToastUtil;
import com.meixiang.view.banner.ConvenientBanner;
import com.meixiang.view.banner.NetworkImageHolderView;
import com.meixiang.view.banner.holder.CBViewHolderCreator;
import com.meixiang.view.banner.listener.OnItemClickListener;
import com.meixiang.view.swipetoloadlayout.base.OnRefreshListener;
import com.meixiang.view.swipetoloadlayout.base.SwipeToLoadLayout;

import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 首页
 * 作者：黑哥 on 2016/3/29 10:06
 */
public class HomeFragment extends BaseFragment implements OnItemClickListener, View.OnClickListener {
    @Bind(R.id.swipe_target)
    RecyclerView homeRecycler;
    @Bind(R.id.refresh)
    SwipeToLoadLayout mRefresh;
    private ImageView ivFinancial, ivService, ivShopping, ivInsurance;
    private LinearLayout linearTrain, linearStaging;
    private ConvenientBanner convenientBanner;


    private View view;
    private ArrayList<String> localImages = new ArrayList<String>();
    private IndexAdapter indexAdapter;
    private View headView;


    //    private String[] bannerUrls={"http://pic28.nipic.com/20130503/10003177_111326031000_2.jpg"
//            ,"http://a0.att.hudong.com/15/08/300218769736132194086202411_950.jpg"
//            ,"http://i9.qhimg.com/t01b3c35c4247fdc250.jpg"
//            ,"http://pic20.nipic.com/20120407/9756907_153426543186_2.jpg"};
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home, container, false);
        ButterKnife.bind(this, view);
        super.onCreateView(inflater, container, savedInstanceState);

        return view;
    }

    @Override
    protected void initTitle() {
    }

    @Override
    protected void initView() {
        indexAdapter = new IndexAdapter();
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        homeRecycler.setLayoutManager(manager);
        homeRecycler.setAdapter(indexAdapter);
        mRefresh.setLoadMoreEnabled(false);
        setHeader(homeRecycler);
        headView=indexAdapter.getHeaderView();
        ivFinancial = ButterKnife.findById(headView, R.id.fragment_home_iv_financial);
        ivService = ButterKnife.findById(headView, R.id.fragment_home_iv_service);
        ivShopping = ButterKnife.findById(headView, R.id.fragment_home_iv_shopping);
        ivInsurance = ButterKnife.findById(headView, R.id.fragment_home_iv_insurance);
        linearTrain = ButterKnife.findById(headView, R.id.fragment_home_linear_train);
        linearStaging = ButterKnife.findById(headView, R.id.fragment_home_linear_staging);
        convenientBanner = ButterKnife.findById(headView, R.id.fragment_home_convenient_banner);
        setEvent();
        homeRecycler.setAdapter(indexAdapter);
        mRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData();
            }
        });
    }


    @Override
    protected void setData() {
        getData();
    }

    private void getData() {
        String url = Config.INDEX_DATA;
        HttpUtils.post(url, new HttpParams(), new HttpCallBack(getActivity()) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                mRefresh.setRefreshing(false);
                Log.e("TAG","输出result=="+result.toString());
                HomeData homeData = AbJsonUtil.fromJson(result.toString(), HomeData.class);
                initBanner(homeData);
                indexAdapter.addAll(homeData.getGoodsList());

            }

            @Override
            public void onError(String code, String message) {
                mRefresh.setRefreshing(false);
                Tool.showTextToast(getActivity(), message);

            }
        });
    }

    @SuppressWarnings("unchecked")
    private void initBanner(HomeData homeData) {
        if (localImages != null && localImages.size() > 0) {
            localImages.clear();
        }
        loadBannerData(homeData);
        convenientBanner.setPages(
                new CBViewHolderCreator<NetworkImageHolderView>() {
                    @Override
                    public NetworkImageHolderView createHolder() {
                        return new NetworkImageHolderView();
                    }
                }, localImages)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator(new int[]{R.mipmap.ic_normal_circle, R.mipmap.ic_select_circle})
                //指示器圆点位置，默认居中
//                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT)
                .setOnItemClickListener(this);
//        convenientBanner.setManualPageable(false);//设置不能手动影响

    }


    private void loadBannerData(HomeData homeData) {
        //本地图片集合
        for (int position = 0; position < homeData.getBannerImgae().size(); position++) {
            localImages.add(homeData.getBannerImgae().get(position));

        }
    }

    // 开始自动翻页
    @Override
    public void onResume() {
        super.onResume();
        //开始自动翻页
        if (localImages.size() > 1) {
            convenientBanner.startTurning(3000);
        }
    }

    // 停止自动翻页
    @Override
    public void onPause() {
        super.onPause();
        //停止翻页
        convenientBanner.stopTurning();
    }


    @Override
    public void onItemClick(int position) {
        //图片轮播点击事件
//        Tool.showTextToast(getActivity(),"点击了第"+position+"个");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    private void setEvent() {
        ivFinancial.setOnClickListener(this);
        ivService.setOnClickListener(this);
        ivShopping.setOnClickListener(this);
        ivInsurance.setOnClickListener(this);
        linearTrain.setOnClickListener(this);
        linearStaging.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        //让商城 未登录可进入
        if(!MXApplication.mApp.hasLogin()&&!v.equals(ivShopping)){
            startActivity(LoginActivity.class);
            AbToastUtil.showToast(activity,"请先登录");
            return;
        }
        if (v.equals(ivFinancial)) {

                startActivity(FundListMainActivity.class);

        } else if (v.equals(ivService)) {
            startActivity(ServiceActivity.class);
        } else if (v.equals(ivShopping)) {
            //美商城
            startActivity(ShoppingHomeActivity.class);
        } else if (v.equals(ivInsurance)) {
            //美保险
            /**
             * 当前如果没有登录就跳 登录界面
             * 当前如果没有实名认证就跳  实名认证界面
             * 否则跳美保险h5
             * */
            if(MXApplication.mApp.getUser().getRealNameAuthentication().equals("0")){
                startActivity(VerifyRealNameActivity.class);
            } else {

                Bundle bundle=new Bundle();
                bundle.putString("url", Config.MEI_INSURANCE);
                bundle.putString("title", "保险");
                startActivity(bundle,WebviewActivity.class);
            }
        } else if (v.equals(linearTrain)) {
            //美容培训
//            startActivity(CosmeticTrainingActivity.class);
            Intent intent=new Intent(activity, CosmeticTrainingActivity.class);
            startActivity(intent);
        } else if (v.equals(linearStaging)) {
            //美分期
//            intent.setClass(getActivity(), StagingActivity.class);
            Tool.showTextToast(getContext(), ContentHint.COMING_SONN);
        }
    }
    private void setHeader(RecyclerView view) {
        View header = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_home_header, view, false);
        indexAdapter.setHeaderView(header);
    }



}
